package com.pnnd.stream;

import com.pnnd.utils.CollectionUtils;
import com.pnnd.utils.MemoryUtils;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.List;

public class ReadOnlyBuffer extends AbstractBuffer implements Buffer {

    private static InputStream inputStream;

    public ReadOnlyBuffer(List<MemorySegment> segmentList,int start,int length){

    }

    @Override
    protected byte[] getByteAddress() {
        return new byte[0];
    }

    @Override
    public InputStream getInputStream() {

        if(inputStream != null){
            return inputStream;
        }

        inputStream = new NdArrayInputStream(this.segments);

        return inputStream;
    }

    @Override
    public OutputStream getOutputStream() {
        throw new NotImplementedException();
    }

    @Override
    public void refresh(int offset) {
        this.offset = offset;
    }

    @Override
    public int getOffset() {
        return this.offset;
    }

    @Override
    public Collection<MemorySegment> getAll() {
        return CollectionUtils.readonly(this.segments);
    }

    @Override
    public MemorySegment get(int index) {
        return this.segments.get(index);
    }

    @Override
    public boolean isContinuous() {

        MemorySegment lastSegment = null;
        for(MemorySegment segment:this.segments){
            if(lastSegment != null && !MemoryUtils.isContinuous(lastSegment,segment)){
                return false;
            }
            lastSegment = segment;
        }
        return true;
    }

    @Override
    public BufferView getView(){

        BufferView view = super.getView();

        return view.asReadOnlyBuffer();
    }

    @Override
    public ByteBuffer getNioBufferReadable() {

        if(this.isContinuous()){
            byte[] bs = this.getByteAddress();

            return ByteBuffer.wrap(bs).asReadOnlyBuffer();
        }

        throw new RuntimeException();
    }
}
